<!--
*@Author: zt
*@Description: 应急预警
*@Date: 2024-09-20
-->
<template>
  <a-layout class="f-h-100 s-bg-white" id="test">
    <u-table-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)"
      >
        <a-col>
          <a-space>
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
          </a-space>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <a-space>
              <u-icon-button itype="add" @click="toEdit">新增</u-icon-button>
              <u-icon-button itype="dismiss" @click="relieveClick()">
                解除预警
              </u-icon-button>
              <u-icon-button itype="delete" @click="delBtn()">
                删除
              </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="loading"
        v-model:pagination="pagenation"
        :scroll="{ y: useTableScroll() }"
        @onDblclick="onDblclick"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
      ></u-table>
    </u-table-content>
  </a-layout>

  <!-- 新增窗口 -->
  <EditAdd
    v-model:open="showAdd"
    style="width: 50vw"
    @success="(showAdd = false), getSearch()"
  />

  <!-- 详情窗口 -->
  <Edit v-model:open="showEdit" wrap-class-name="full-modal" :keyid="keyid" />

</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch } from 'vue';
import { _IFormEl } from '@/components/common/form/interface';
import { ColProps, FormItemProps, TableColumnProps } from 'ant-design-vue';
import { useTableScroll } from '@/hooks/useTable';
import { alertC, messageC } from '@/util/common';
import { chatEventBus } from '@/util/eventBus'
import EditAdd from '@/views/index/index/components/emergency/editAdd.vue';
import Edit from '@/views/index/index/components/emergency/edit.vue';
import UIconFont from '@/components/common/iconfont/IconFont.vue';
import * as dynamicFormsApi from '@/service/emergency/dynamicForms/index';
import * as emergencyWarningApi from '@/service/emergencyWarning/index';

let keyid = ref('');

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`,
});
let searchF = ref<any>({
  model: {
    keywords: '',
  },
});

let showEdit = ref<boolean>(false);
let showAdd = ref<boolean>(false);
const tabSelData = ref<any[]>([]);
const formItemProps: FormItemProps = {
  wrapperCol: { span: 24 },
};
const searchEl: Array<_IFormEl> = [
  {
    label: '关键字',
    key: 'keywords',
    element: 'input',
    col: { span: 4 },
    formItemProps: {
      ...formItemProps,
      labelWidth: '60px',
    },
    componentProps: {
      placeholder: '预警标题'
    }
  },
];

// 列表
let tabData = ref([]);
let loading = ref<boolean>(false);
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    customRender: ({ text, record, index }) => {
      return index + 1;
    },
  },
  { dataIndex: 'title', title: '预警标题', width: 150, align: 'center' },
  {
    dataIndex: 'warnLevel',
    title: '预警等级',
    width: 150,
    align: 'center',
    customRender: ({ text }) => {
      let levelLabel = {
        1: 'I级应急响应',
        2: 'II级应急响应',
        3: 'III级应急响应',
        4: 'IV级应急响应',
      };
      return levelLabel[text] || '';
    },
  },
  {
    dataIndex: 'group',
    title: '对应群聊',
    width: 130,
    align: 'center',
    customRender: ({ text, record }) => {
      console.log("🚀 ~ record:", record)
      const tgroupchatList = record['tgroupchatList'] || []
      return (tgroupchatList).length > 0
        ? h(UIconFont, {
            type: 'icon-zaixiangoutong',
            style: 'color: #1890ff;cursor: pointer',
            title: tgroupchatList[0]['groupNames'],
            onClick: function () {
              chatEventBus.emit('openGroup', { ...tgroupchatList[0], types: 1 })
            },
          })
        : '';
    },
  },
  {
    dataIndex: 'warnTime',
    title: '预警时间',
    width: 150,
    align: 'center',
    customRender: ({ text }) => {
      return (text || '').split(' ')[0];
    },
  },
  {
    dataIndex: 'relieveFlag',
    title: '解除状态',
    width: 150,
    align: 'center',
    customRender: ({ text, record }) => {
      let colors;
      if (text == 1) {
        colors = '#73D13D';
        return h('span', { style: { color: colors } }, '已解除');
      } else {
        if (record.warnLevel == '1') {
          colors = '#FF4D4F';
        } else if (record.warnLevel == '2') {
          colors = '#FA8C16';
        } else if (record.warnLevel == '3') {
          colors = '#F3CC09';
        } else if (record.warnLevel == '4') {
          colors = '#1890FF';
        }
        return h('span', { style: { color: colors } }, '未解除');
      }
    },
  },
  {
    dataIndex: 'content',
    title: '预警原因',
    align: 'center',
    customRender: ({ text }) => {
      return (text || '').split(' ')[0];
    },
  },
]);

// 查询数据
const getSearch = async (index?) => {
  let tform = JSON.parse(JSON.stringify(searchF.value));
  if (index == 1) {
    pagenation.current = 1;
  }
  tform.current = pagenation.current;
  tform.size = pagenation.pageSize;
  loading.value = true;
  try {
    const res = await emergencyWarningApi.page({ ...tform });
    if (res.code == 0) {
      tabData.value = res.data.records;
    }
  } catch (error) {}
  loading.value = false;
};

const toEdit = () => (showAdd.value = true);

// 解除预警
const relieveClick = () => {
  if (tabSelData.value.length == 0) {
    alertC('请先选择要解除预警的数据!', 'warning');
    return;
  }
  let ids = tabSelData.value.map(item => item.keyid);
  alertC('请确认解除预警的数据?', 'confirm').then(async () => {
    try {
      const res = await emergencyWarningApi.updateStatus({
        ids: ids.join(','),
      });
      if (res.code == 0) {
        getSearch(1);
        messageC(res.msg, 'success');
      } else {
        alertC(res.msg, 'warning');
      }
    } catch (error) {}
  });
};

// 删除
const delBtn = () => {
  if (tabSelData.value.length == 0) {
    alertC('请先选择要删除的数据!', 'warning');
    return;
  }
  let ids = tabSelData.value.map(item => item.keyid);
  alertC('确认删除选中的数据?', 'confirm').then(async () => {
    try {
      const res = await emergencyWarningApi.del({ ids: ids.join(',') });
      if (res.code == 0) {
        getSearch(1);
        messageC(res.msg, 'success');
      } else {
        alertC(res.msg, 'warning');
      }
    } catch (error) {}
  });
};

//行双击
const onDblclick = record => {
  keyid.value = record['keyid'];
  showEdit.value = true;
};

onMounted(async () => {
  await getSearch(1);
});

defineExpose({
  toEdit,
});
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
